package com.mfs.common.utills;

import com.mfs.common.holder.ThreadHolder;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 任务工具类
 * @author mfs
 * @date 2022/07/11
 * */
public class TaskUtil {
    // 同名任务计数器
    private static Map<String, Counter> counterMap = new ConcurrentHashMap<>();
    public static void start(Runnable task) {
        start(task, generateName(task),false);
    }

    private static String generateName(Runnable task) {
        String name = task.getClass().getSimpleName();
        Counter counter = counterMap.get(name);
        if (counter == null) {
            counter = new Counter(name);
        }
        int id = counter.increase();
        return name + "---" + id;
    }

    public static void daemonStart(Runnable task) {
        start( task, generateName(task), true);
    }

    public synchronized static void start(Runnable task, String name, boolean isDaemon) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    task.run();
                } finally {
                    if (task instanceof Closeable) {
                        try {
                            ((Closeable)task).close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    ThreadHolder.remove(Thread.currentThread());
                }
            }

        };

        thread.setName(name);
        thread.setDaemon(isDaemon);
        thread.start();
        ThreadHolder.add(thread);
    }
}
